package com.xdcplus.web.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.xdcplus.web.service.DataService;
import com.xdcplus.web.service.minio.MinioService;
import io.minio.GetObjectResponse;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class DataServiceImpl implements DataService {

    @Autowired
    protected MinioService minioService;


    @Override
    public List<List<String>> getFactoryProduce(String pathName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectResponse getObjectResponse = minioService.pullFile(
                String.format("data/factory/produce/%s.xlsx",pathName)
        );
        return readExcelData(getObjectResponse);
    }

    @Override
    public List<List<String>> readExcelData(GetObjectResponse getObjectResponse) {
        List<List<String>> rowResultList = new ArrayList<>();
        EasyExcel.read(
                getObjectResponse,
                new ReadListener<Map<Integer,String>>() {

                    @Override
                    public void invoke(Map<Integer,String> dataMap, AnalysisContext analysisContext) {
                        List<String> rowDataList = new ArrayList<>();
                        dataMap.forEach((key,value)->{
                            rowDataList.add(key,value);
                        });
                        rowResultList.add(rowDataList);
                        log.info("rowDataList:{}",rowDataList);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                    }

                }).sheet(0).doRead();

        for (int i = 1; i < rowResultList.size(); i++) {
            int preI = i -1;
            List<String> rowList = rowResultList.get(i);
            List<String> preRowList = rowResultList.get(preI);
            for (int j = 0; j < rowList.size(); j++) {
                String rowItem = rowList.get(j);
                if (rowItem==null) {
                    rowList.set(j,preRowList.get(j));
                }
            }
            log.info("rowList:{}",rowList);
        }

        return rowResultList;

    }


}
